package com.bwie.filter;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/**
 * @Author:杨珂
 * @CreateTime: 2025-03-25
 */
@Order(-1)
@Configuration
public class MyGlobalFilter implements GlobalFilter {

    /**
     * 网关全局异常
     * 1.先实现GlobalFilter
     * 2.ctrl+O  实现filter
     * 3.//**1 获取参数
     * 4.设置白名单
     * 5.检查token 解析token
     * 6.token续期
     * 7.放行
     */
    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //**1 获取参数
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String url = request.getURI().getPath().toString();
        System.out.println("url=" + url);

        //**2白名单
        if (url.contains("/login") || url.contains("/addUser")) {
            System.out.println("白名单：" + url);
            return chain.filter(exchange);
        }
        if (url.contains("/uploadImage")) {
            System.out.println("白名单：" + url);
            return chain.filter(exchange);
        }

        //**3检查token
        String token = request.getHeaders().getFirst("token");
        if (token == null) {
            System.out.println("token为空：" + token);
            //UNAUTHORIZED = 错误代码401 报401 就是网关出现问题了
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer id = body.get("id", Integer.class);

        String tokenKey = "token-" + id;
        String redisToken = redisTemplate.opsForValue().get(tokenKey);
        if (redisToken == null) {
            System.out.println("token已经过期：" + url);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        if (!token.equals(redisToken)) {
            System.out.println("token错误了：" + url);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //--4 token续期
        redisTemplate.expire(tokenKey, 120, TimeUnit.MINUTES);

        //--5 放行
        System.out.println("放行：" + url);
        return chain.filter(exchange);//是的这个页面是注册
    }
}
